package com.dk.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;

@WebFilter(value = "/*", dispatcherTypes= {DispatcherType.FORWARD,DispatcherType.REQUEST})
public class FilterDemo implements Filter {

    private List<String> list =  new ArrayList<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        list.add("操");
        list.add("操你妈");
        list.add("傻逼");
        list.add("港独");
        list.add("台独");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        String rname = request.getParameter("rname");
        //如果rname不为空
        if(rname != null && !"".equals(rname)) {
            //遍历上面的list集合
            for (int i = 0; i < list.size(); i++) {
                //如果rname中包含list里的字符
                if (rname.contains(list.get(i))) {
                    //确定这个字符的长度，并且搞一个空字符串
                    int u = list.get(i).length();
                    String s = "";
                    //遍历，如果空字符串长度小于字符长度，则不 += 星星
                    for (int j = 0; j < u; j++) {
                        s += "*";
                    }
                    //将rname中 的字符替换为星星
                    String replaceAll = rname.replaceAll(list.get(i),s);
                    rname = replaceAll;
                }
            }
            request.setAttribute("rname",rname);
        }
        //放在最外面的循环,检查了半小时……
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}

